package com.liuyz.reader_;

import org.junit.Test;

import java.io.FileReader;
import java.io.IOException;

public class 文件字符输入流 {

    // 按字符进行读取
    @Test
    public void read_1() {
        String path = "d:\\test.txt";
        FileReader fileReader = null;
        int len = 0;
        try {
            fileReader = new FileReader(path);
            while ((len = fileReader.read()) != -1) {
                System.out.print((char) len);
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fileReader) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 按字符数组进行读取，将读取到的结果保存在字符数组
    @Test
    public void read_2() {
        String path = "d:\\test.txt";
        FileReader fileReader = null;
        // 使用字符数组来保存读取到的数据
        char[] arr = new char[8];
        int len = 0;
        try {
            fileReader = new FileReader(path);
            while ((len = fileReader.read(arr)) != -1) {
                System.out.print(new String(arr, 0, len));
            }

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (null != fileReader) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
